package book.crypto;

import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

/**
 * 完成密钥的包装和解包操作
 */
public class CipherTest {

	public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
		
		KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
		SecretKey secretKey = keyGenerator.generateKey();
		System.out.println(new BigInteger(secretKey.getEncoded()));
		
		//算法、工作模式、填充模式
		//DES/CBC/PKCS5PADDING
		Cipher c= Cipher.getInstance("DES");
		
		//包装操作
//		c.init(Cipher.WRAP_MODE, secretKey);
//		byte[] k = c.wrap(secretKey);
//		System.out.println(new BigInteger(k));
//		
//		//解包操作
//		c.init(Cipher.UNWRAP_MODE, secretKey);
//		Key key = c.unwrap(k, "DES", Cipher.SECRET_KEY);
//		System.out.println(new BigInteger(key.getEncoded()));
		
		//加密操作
		c.init(Cipher.ENCRYPT_MODE, secretKey);
		System.out.println(new BigInteger("DES DATA".getBytes()));
		byte[] input = c.doFinal("DES DATA".getBytes());
		System.out.println(new BigInteger(input));
		
		//解密操作
		c.init(Cipher.DECRYPT_MODE, secretKey);
		byte[] output = c.doFinal(input);
		System.out.println(new BigInteger(output));
	}
}
